<template>
  <div>

    <!--header-->
    <el-row :gutter="20">
      <el-col :span="3">
        <div class="top5">
          <p class="top-text">周报筛选: </p>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="top5">
          <el-dropdown @command="handleGroupChange">
          <span class="el-dropdown-link top-text blue-text">
            {{curGroupName}}<i class="el-icon-caret-bottom el-icon--right"></i>
          </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="item.id" v-for="item in myGroups" :key="item.id">{{item.name}}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="div-right">
          <el-date-picker
            v-model="week"
            type="week"
            format="yyyy 年第 WW 周"
            placeholder="选择周"
            :picker-options="options"
            @change="weekOnChange"
          >
          </el-date-picker>
        </div>
      </el-col>
      <el-col :span="9">
        <div class="div-right">
          <el-button type="success" @click="postNew">写周报</el-button>
        </div>
      </el-col>
    </el-row>

    <div style="width: 98%; margin: auto">
      <!--posts and comments-->
      <div class="grayBoundTop20" v-for="(item, index) in postList" style="padding: 20px 5px 0 5px">

        <post :name="item.name" :content="item.content" :date="item.createTime" :attachments="item.attachments"></post>

        <div class="div-margin20">
          <comment v-for="comment in item.comments" :name="comment.userName" :content="comment.content"
                   :date="comment.date" :key="comment.id"></comment>
        </div>

        <div class="div-margin10" v-show="showCommentBox[index]">
          <el-form ref="form" label-width="40px">
            <el-input type="textarea" v-model="commentBox[index]"></el-input>
          </el-form>
        </div>

        <div style="padding: 20px 5px 0 5px; text-align: right">
          <el-button v-show="showCommentBox[index]" @click="sendComment(index)" size="small" type="primary">确定
          </el-button>
          <el-button @click="toggleCommentBox(index)" size="small">{{showCommentBoxButtonText[index]}}</el-button>
          <el-button v-if="editable" @click="toggleReEditDialog(index)" size="small">重新编辑</el-button>
        </div>
      </div>
      <!--hr-->

      <!--members of group-->
      <div class="grayBoundTop20">
        <h2>项目成员</h2>
        <el-button :type="item.hasSubmitted? 'success': 'danger'" v-for="(item,index) in members"
                   @click="viewMember(item.id)" :key="item.id">{{item.name}}
        </el-button>
      </div>
      <!--add button-->
    </div>
    <!--div for space-->
    <div class="div-margin20"></div>

    <!--edit dialog-->
    <el-dialog title="重新编辑" :visible.sync="dialogEditVisible">
      <div id="editor" style="padding-left: 5px;padding-right: 5px">
        <mavon-editor
          v-model="markdown_value"
          default_open="edit"
          :subfield="false"
          :toolbars="toolbars"
          @change="markChange"
          style="height: 100%"></mavon-editor>

      </div>
      <!--upload-->
      <div class="div-margin20" style="width: 300px; padding-left: 10px">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          name="file"
          :on-success="handleFileUploadSuccess"
          :on-remove="handleFileUploadRemove"
          :on-error="handleFileUploadError"
          :file-list="uploadFileList">
          <el-button size="small" type="primary">添加附件</el-button>
          <div slot="tip" class="el-upload__tip" v-show="uploadFileList.length>0">文件列表</div>
        </el-upload>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import {
    Input,
    Dialog,
    Dropdown,
    DropdownItem,
    DropdownMenu,
    Button,
    Row,
    Col,
    Form,
    FormItem,
    DatePicker,
    Upload,
    Tag,
  } from 'element-ui';
  import {mavonEditor} from 'mavon-editor'
  import Post from "../../components/post.vue";
  import Comment from "../../components/comment.vue"
  import * as api_group from '../../api/group'
  import * as api_post from '../../api/post'
  import * as api_comment from '../../api/comment'
  import * as $ from '../../utils/HHUtil';
  import {mapGetters} from 'vuex';

  export default {
    props: {},
    components: {
      Post,
      Comment,
      mavonEditor,
      'el-upload': Upload,
      'el-input': Input,
      'el-form': Form,
      'el-form-item': FormItem,
      'el-button': Button,
      'el-dropdown': Dropdown,
      'el-dropdown-item': DropdownItem,
      'el-dropdown-menu': DropdownMenu,
      'el-row': Row,
      'el-col': Col,
      'el-dialog': Dialog,
      'el-date-picker': DatePicker,
      'el-tag': Tag,
    },
    computed: {
      ...mapGetters(['userInfo']),
    },
    data() {
      return {
        week: new Date(),
        weekStr: '',
        editable: false,
        curWeek: 0,
        curYear: 0,
        curUserId: 0,
        curGroupName: '',
        cur: new Date(),
        options: {
          firstDayOfWeek: 1,
          shortcuts: [{
            text: '本周',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '上周',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }, {
            text: '上上周',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7 * 2);
              picker.$emit('pick', date);
            }
          }],
        },
        postList: [],
        members: [],
        commentList: [
          {name: '穆鹏飞', userId: 1, comment: '', commentDate: ''}
        ],
        commentBox: [],
        showCommentBox: [],
        showCommentBoxButtonText: [],
        dialogEditVisible: false,
        myGroups: [],
        groupInfo: {},
        uploadFileList: [],
        markdown_value: '',
        html_value: '',
        editingPostId: 0,
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: true, // 标记
          superscript: true, // 上角标
          subscript: true, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: false, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: true, // 沉浸式阅读
          htmlcode: true, // 展示html源码
          help: true, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: true, // 下一步
          trash: true, // 清空
          save: true, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: true, // 导航目录
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: true, // 预览
        },
        uploadUrl:''
      }
    },
    methods: {
      weekOnChange(week) {
        console.log('change week', week);
        let dateArr = week.split(/\s/);
        console.log(dateArr);
        if (dateArr.length === 4) {
          console.log('change to week', week);
          this.$router.push({
            name: 'review',
            params: {groupId: this.curGroupId, week: dateArr[2], year: dateArr[0], userId: this.curUserId}
          });
        }
      },
      viewMember(id) {
        this.$router.push({
          name: 'review',
          params: {userId: id, week: this.curWeek, year: this.curYear, groupId: this.curGroupId}
        });
      },
      toggleCommentBox(index) {
        console.log('click on ', index, '->', this.showCommentBox[index]);
        this.showCommentBox.splice(index, 1, !this.showCommentBox[index]);
        this.showCommentBoxButtonText.splice(index, 1, this.showCommentBox[index] ? '不写评论' : '写评论');
      },
      sendComment(index) {
        const commentStr = this.commentBox[index];

        let postId = this.postList[index].id;
        let form = {
          postId,
          'content': commentStr
        };
        api_comment.sentComment(form).then(() => {
          this.$notify.success('提交成功');
          //send commentStr
          this.commentBox.splice(index, 1, '');
          this.showCommentBox.splice(index, 1, !this.showCommentBox[index]);
          this.showCommentBoxButtonText.splice(index, 1, this.showCommentBox[index] ? '不写评论' : '写评论');
          this.refresh();
        }).catch(err => {
          this.$message.error("提交评论失败：" + err.errmsg);
        })
      },
      postNew() {
        this.$router.push({
          name: 'post',
          params: {groupId: this.groupInfo.id}
        });
      },
      markChange(value, render) {
        this.html_value = render;
      },
      handleFileUploadSuccess(response, file, fileList) {
        console.log('上传文件', fileList);
        this.uploadFileList = fileList.map(f => {
          if ($.hasValue(f.response)) {
            return {name: f.response.data.fileName, url: f.response.data.url, id: f.response.data.id}
          } else {
            return {name: f.name, url: f.url, id: f.id};
          }
        });
      },
      handleFileUploadRemove(file, fileList) {
        console.log('移除文件', fileList);
        this.uploadFileList = fileList.map(f => {
          if ($.hasValue(f.response)) {
            return {name: f.response.data.fileName, url: f.response.data.url, id: f.response.data.id}
          } else {
            return {name: f.name, url: f.url, id: f.id};
          }
        });
      },
      handleFileUploadError(response, file, fileList) {
        this.$message.error("上传文件失败: " + response.errmsg);
      },
      toggleReEditDialog(index) {
        this.editingPostId = this.postList[index].id;
        this.markdown_value = this.postList[index].markContent;
        this.uploadFileList = this.postList[index].attachments
          .map(a => {
            return {url: a.url, name: a.fileName, id: a.id};
          });
        this.dialogEditVisible = !this.dialogEditVisible;
      },
      cancelEdit() {
        this.dialogEditVisible = false;
      },
      confirmEdit() {
        let form = {
          postId: this.editingPostId,
          content: this.html_value,
          markContent: this.markdown_value,
          attachments: this.uploadFileList.map(f => f.id)
        };
        api_post.reedit(form).then(data => {
          this.$notify.success('修改成功！');
          this.dialogEditVisible = false;
          this.updatePostOfWeek();
        }).catch(err => {
          this.$message.error("提交修改失败：" + e.errmsg);
        })
      },
      getMyGroupsInfo() {
        api_group.getMyGroupList().then(data => {
          this.myGroups = data;
        }).catch(err => {
          this.$message.error("获取项目列表失败：" + err.errmsg);
        });
      },
      getGroupInfo() {
        api_group.getGroupInfo({id: this.curGroupId}).then(data => {
          this.groupInfo = data;
          this.curGroupName = this.groupInfo.name;
        }).catch(err => {
          this.$message.error("获取项目组信息失败：" + err.errmsg);
        });
      },
      handleGroupChange(id) {
        this.$router.push({name: 'review', params: {groupId: id, year: this.curYear, week: this.curWeek}});
      },
      getMemberSubmitStatus() {
        let submitted = [];
        this.members = [];
        api_group.getAllPostersOfGroupInWeek({
          groupId: this.curGroupId,
          year: this.curYear,
          week: this.curWeek
        }).then(data => {
            submitted = data;
//          向数组添加元素
            return api_group.getAllMembers({
              id: this.curGroupId
            })
          })
          .then(data => {
//            筛选用户
            let curMembers = data;
//            加入所有用户
            for (let i = 0; i < submitted.length; i++) {
              let member = {name: curMembers[i].name, id: curMembers[i].id, hasSubmitted: true};
              this.members.push(member);
            }
//            筛选加入所有未交用户
            console.log(this.curWeek, $.weekOfYear(new Date()));
            console.log(this.curWeek, $.weekOfYear(new Date()),this.curWeek !== $.weekOfYear(new Date()));
            if (this.curWeek !== $.weekOfYear(new Date())) {
              return;
            }
            console.log(curMembers);
            for (let i = 0; i < curMembers.length; i++) {
              let member = {name: curMembers[i].name, id: curMembers[i].id, hasSubmitted: false};
              let flag = false;
              for (let j = 0; j < submitted.length; j++) {
                if (curMembers[i].id === submitted[j].id) {
                  flag = true;
                  break;
                }
              }
              if (!flag) {
                this.members.push(member);
              }
            }
          })
          .catch(err => {
            this.$message.error("获取项目成员信息失败：" + err.errmsg);
          })


      },
      updatePostOfWeek() {
        let form = {
          groupId: this.curGroupId,
          year: this.curYear,
          week: this.curWeek,
          userId: this.curUserId
        };
        api_post.getUserPostOfWeek(form).then(data => {
          this.postList = data;
          this.loadCommentBox();
        }).catch(err => {
          this.$message.error("获取历史提交失败：" + err.errmsg);
        })
      },
      loadCommentBox() {
        for (let i = 0; i < this.postList.length; i++) {
          this.commentBox.splice(i, 1, '');
          this.showCommentBox.splice(i, 1, false);
          this.showCommentBoxButtonText.splice(i, 1, '写评论');
        }
      },
      initParams() {
        let params = this.$route.params;
        this.curGroupId = params.groupId;
        this.curYear = params.year;
        this.curWeek = params.week;
        this.curUserId = params.userId;
        this.editable = parseInt(this.curWeek) === $.weekOfYear(new Date()) && parseInt(this.curUserId) === this.userInfo.id;
        //todo
        console.log(this.$hhUtil.getFirstDayOfWeek(this.curWeek, this.curYear));
        this.week = this.$hhUtil.getFirstDayOfWeek(this.curWeek, this.curYear);
      },
      refresh() {
//        reset comments
        this.initParams();
        this.updatePostOfWeek();
        this.getMyGroupsInfo();
        this.getGroupInfo();
        this.getMemberSubmitStatus();
      }
    },
    created() {
    },
    mounted() {
      let host = window.location.host;
      this.uploadUrl = 'http://' + host + "/sei/upload";
      this.refresh();
    }
  }
</script>

<style>

  .top-text {
    font-size: 16px;
    margin-top: 0;
  }

  .blue-text {
    color: #20a0ff;
  }

  .top5 {
    margin-top: 5px;
  }

</style>
